import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

FACTOR = 2

plt.figure(figsize=[18, 6])
spr = 1
spc = 3
spn = 0

# scatter
spn += 1
plt.subplot(spr, spc, spn)
centers = np.array([[0.5, 0.75], [1.2,1.2], [1.5, 2], ])
n_centers = len(centers)
stds = np.array([0.3, 0.4, 0.5])
cmap = plt.cm.get_cmap('rainbow', n_centers)
from sklearn.datasets import make_blobs
x, y = make_blobs(n_samples=450, n_features=2,
                  centers=centers,
                  cluster_std=stds,
                  random_state=666)
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=cmap, s=1)
plt.scatter(centers[:, 0], centers[:, 1], marker='x', s=100, c=range(n_centers), cmap=cmap)


# circles from mu and FACTOR * sigma
def x_get_y_of_circle(x0, r, x):
    y = (abs(r ** 2 - (x - x0) ** 2)) ** 0.5
    return y

def x_draw_circle(x0, y0, r, color):
    x = np.linspace(x0 - r, x0 + r, 200)
    y = x_get_y_of_circle(x0, r, x)
    y_pos = y + y0
    y_neg = - y + y0
    plt.plot(x, y_pos, color=color)
    plt.plot(x, y_neg, color=color)

for i, cent in enumerate(centers):
    x_draw_circle(cent[0], cent[1], FACTOR * stds[i], cmap(i))

# GMM
from sklearn.mixture import GaussianMixture
model = GaussianMixture(n_components=n_centers,
                        covariance_type='full',
                        random_state=666)
model.fit(x)
centers_reg = model.means_
print(centers)
print(centers_reg)
stds_reg = np.array(model.covariances_)[:, 0, 0]
print(stds)
print(stds_reg)
plt.scatter(centers_reg[:, 0], centers_reg[:, 1], marker='x', s=100, color='k')
for i, cent in enumerate(centers_reg):
    x_draw_circle(cent[0], cent[1], FACTOR * stds_reg[i], color='k')
# metrics
from sklearn.metrics import accuracy_score
print(f'Score = {model.score(x, y)}')
h = model.predict(x)
print(f'Acc = {accuracy_score(y, h)}')

# hist for x
spn += 1
ax = plt.subplot(spr, spc, spn)
df = pd.DataFrame({'c1': x[y == 0, 0],
                   'c2': x[y == 1, 0],
                   'c3': x[y == 2, 0]})
df.plot(kind='hist', ax=ax,
        bins=50, alpha=0.5,  # ATTENTION df.plot kind='hist': bins alpha
        cmap=cmap)
ax.scatter(centers[:, 0], np.zeros(n_centers), marker='x', c=range(n_centers), cmap=cmap, s=100)
ax.scatter(centers_reg[:, 0], np.zeros(n_centers), marker='x', color='k', s=100)

# hist for y
spn += 1
ax = plt.subplot(spr, spc, spn)
df = pd.DataFrame({'c1': x[y == 0, 1],
                   'c2': x[y == 1, 1],
                   'c3': x[y == 2, 1]})
df.plot(kind='hist', ax=ax, bins=50, alpha=0.5, cmap=cmap)
ax.scatter(centers[:, 1], np.zeros(n_centers), marker='x', c=range(n_centers), cmap=cmap, s=100)
ax.scatter(centers_reg[:, 1], np.zeros(n_centers), marker='x', color='k', s=100)

# Finally show all drawings.
plt.show()
